package org.csu.mypetstore.controller;


import org.csu.mypetstore.aspect.LogAnnotation;
import org.csu.mypetstore.commonResponse.CommonResponse;
import org.csu.mypetstore.domin.Account;
import org.csu.mypetstore.domin.Address;
import org.csu.mypetstore.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;

import static org.csu.mypetstore.controller.AccountController.isLogin;

@RestController
@RequestMapping("/addresses")
public class AddressController {
    @Autowired
    AddressService addressService;
    //查看我的所有地址
    @LogAnnotation(module="addresses",operation = "查看地址")
    @GetMapping("")
    public CommonResponse<List<Address>> getAddressListByUsername(HttpSession session){
        CommonResponse<Account> commonResponse=isLogin(session);
        if (commonResponse.getStatus() == 0) {
            return CommonResponse.createForError("未登录");
        }
        return addressService.getAddressListByUsername(commonResponse.getData().getUserid());
    }
    //新增地址
    @LogAnnotation(module="addresses",operation = "新增地址")
    @PostMapping("")
    public CommonResponse<Address> addAddress(@RequestBody Address address,HttpSession session){
        CommonResponse<Account> commonResponse=isLogin(session);
        if (commonResponse.getStatus() == 0) {
            return CommonResponse.createForError("未登录");
        }
        address.setUsername(commonResponse.getData().getUserid());
        return addressService.addAddress(address);
    }
    //更改地址
    @LogAnnotation(module="addresses",operation = "修改地址")
    @PutMapping("")
    public CommonResponse<Address> updateAddress(@RequestBody Address address,HttpSession session){
        CommonResponse<Account> commonResponse=isLogin(session);
        if (commonResponse.getStatus() == 0) {
            return CommonResponse.createForError("未登录");
        }
        address.setUsername(commonResponse.getData().getUserid());
        return addressService.updateAddress(address);
    }
    //删除地址
    @LogAnnotation(module="addresses",operation = "删除地址")
    @DeleteMapping("/{id}")
    public CommonResponse<String> deleteAddress(@PathVariable int id,HttpSession session){
        CommonResponse<Account> commonResponse=isLogin(session);
        if (commonResponse.getStatus() == 0) {
            return CommonResponse.createForError("未登录");
        }
        return addressService.deleteAddress(id);
    }
}
